package nio.nio_chat;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

/**
 * @author charwayH
 * 目标:服务端群聊系统
 */
@SuppressWarnings("all")
public class Client {
    // 1.定义客户端相关属性
    private Selector selector;
    private static int PORT = 9999;
    private SocketChannel sChannel;

    // 2.初始化客户端信息
    public Client() {
        try {
            // a.创建选择器
            selector = Selector.open();
            // b.连接服务端
            sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", PORT));
            // c.设置非阻塞模式
            sChannel.configureBlocking(false);
            sChannel.register(selector, SelectionKey.OP_READ);
            System.out.println("当前客户端准备完成:");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        final Client client = new Client();
        // 定义一个线程专门负责服务端发送过来的读线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    while (true) {
                        client.readInfo();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        Scanner sc = new Scanner(System.in);
        while (sc.hasNextLine()) {
            String msg = sc.nextLine();
            client.sendToServer(msg);
        }

    }

    private void sendToServer(String msg) {
        try {
            sChannel.write(ByteBuffer.wrap(("charwayH :" + msg).getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void readInfo() throws IOException {
        if (selector.select() > 0) {
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey sk = iterator.next();
                if (sk.isReadable()) {
                    SocketChannel sChannel = (SocketChannel) sk.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    sChannel.read(buffer);
                    buffer.flip();
                    System.out.println(new String(buffer.array()));
                }
                iterator.remove();
            }
        }
    }
}
